<template>
  <el-container>
    <el-container>
      <el-main>
        <!-- dialog -->
        <el-dialog
          title="学生信息导入"
          :visible.sync="dialogVisible"
          width="30%"
        >
          <el-form>
            <el-form-item label="请选择Excel文件">
              <el-upload
                :auto-upload="true"
                :multiple="false"
                :limit="1"
                :on-exceed="fileUploadExceed"
                :on-success="fileUploadSuccess"
                :on-error="fileUploadError"
                :action="BASE_API + '/admin/student/importStudentData'"
                name="file"
                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <span style="margin-left: 30px"
                  >点击此处<a
                    class="downFileTemplate"
                    href="javascript:void(0);"
                    @click="downStudentExcelTemplate"
                    >下载模板</a
                  ></span
                >
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false"> 取消 </el-button>
          </div>
        </el-dialog>

        <el-row class="function-button" style="text-align: center">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增按钮</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-button type="danger" size="small" round @click="batchDelStudent()"
            >批量删除</el-button
          >
          <!-- Excel导入按钮 -->
          <el-button
            @click="dialogVisible = true"
            type="primary"
            round
            size="small"
          >
            一键导入
          </el-button>

          <el-button
            type="success"
            size="small"
            round
            @click="exportStudentData()"
            >一键导出</el-button
          >
        </el-row>

        <el-collapse accordion class="accordion">
          <el-collapse-item>
            <template slot="title">
              筛选<i class="header-icon el-icon-info"></i>
            </template>
            <div>
              <el-button
                class="queryBtn"
                round
                type="success"
                style="margin-left: 10px"
                @click="queryByCondition"
                >查询</el-button
              >
              <el-button
                class="queryBtn"
                round
                style="margin-left: 10px"
                type="warning"
                @click="resetStudentQueryParams"
                >重置</el-button
              >
            </div>
            <el-input
              style="width: 20%; margin-left: 40px"
              placeholder="输入学生学号"
              size="samll"
              prefix-icon="el-icon-search"
              v-model="id"
            >
            </el-input>
            <el-input
              style="width: 20%; margin-left: 40px"
              placeholder="输入学生姓名"
              size="samll"
              prefix-icon="el-icon-search"
              v-model="name"
            >
            </el-input>
            <el-cascader
              style="margin-left: 10px; width: 30%"
              placeholder="请选择院系/专业/班级"
              v-model="DepAndMajorTree"
              key="id"
              :options="depAndMajorMenu"
              :props="optionProps"
              clearable
              ref="departmentAndMajorTree"
            ></el-cascader>
          </el-collapse-item>
        </el-collapse>

        <template>
          <el-table
            ref="studentTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="students"
            fit
            max-height="700"
            size="medium "
            class="tableStyle"
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="头像">
                    <el-avatar
                      shape="square"
                      :key="props.row.avatar"
                      :size="150"
                      alt="学生头像"
                      :src="BASE_API + '/' + props.row.avatar"
                    ></el-avatar>
                  </el-form-item>
                  <el-form-item label="学号：">
                    <span>{{ props.row.id }}</span>
                  </el-form-item>
                  <el-form-item label="姓名：">
                    <span>{{ props.row.name }}</span>
                  </el-form-item>
                  <el-form-item label="性别：">
                    <span>{{ props.row.gender === 1 ? '男' : '女' }}</span>
                  </el-form-item>
                  <el-form-item label="年龄：">
                    <span>{{ props.row.age }}</span>
                  </el-form-item>
                  <el-form-item label="班级：">
                    <span>{{ props.row.classroom }}</span>
                  </el-form-item>
                  <el-form-item label="专业：">
                    <span>{{ props.row.major }}</span>
                  </el-form-item>
                  <el-form-item label="院系：">
                    <span>{{ props.row.department }}</span>
                  </el-form-item>
                  <el-form-item label="联系电话：">
                    <span>{{ props.row.phone }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column type="selection" width="55" reserve-selection>
            </el-table-column>
            <el-table-column prop="id" label="学号" width="150">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120">
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="120">
            </el-table-column>
            <el-table-column prop="gender" label="性别" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.gender === 1 ? '男' : '女' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="classroom" label="班级" width="200">
            </el-table-column>
            <el-table-column prop="major" label="专业" width="200">
            </el-table-column>
            <el-table-column prop="department" label="院系" width="200">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="delStudent(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next, jumper"
            :total="studentIPage.total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { mapGetters } from 'vuex';
// 节流函数
import throttle from 'lodash/throttle';
import jsCookie from 'js-cookie';
export default {
  name: 'StudentMng',
  data() {
    return {
      BASE_API: process.env.VUE_APP_BASE_API, // 前缀
      dialogVisible: false,
      currentPage: 1, // 当前页
      pageSize: 10, // 每页显示条数
      condition: {}, // 保存查询
      id: undefined, // 学生编号
      name: '', // 学生姓名
      students: [], // 学生信息集合
      departments: [], // 院系集合
      majors: [], // 专业集合
      multipleSelection: [], // 勾选行信息
      loading: false, // 加载
      DepAndMajorTree: [], // 院系专业树
      // 院系专业树映射规则
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true,
      },
      BASE_API: process.env.VUE_APP_BASE_API, // 前缀
    };
  },
  computed: {
    ...mapGetters('StudentMng', [
      'studentIPage',
      'studentList',
      'depAndMajorMenu',
    ]),
    ...mapGetters('AcademyMng', ['departmentListForIdAndName']),
  },
  watch: {
    studentList() {
      this.$set(this, 'students', this.studentList);
      this.loading = false;
    },
    studentIPage() {
      this.currentPage = this.studentIPage.currentPage;
      this.pageSize = this.studentIPage.pageSize;
    },
  },
  mounted() {
    this.getStudentList();
    this.getDepAndMajorAndClassroomMenu();
  },
  methods: {
    // 重置查询参数
    resetStudentQueryParams() {
      this.id = undefined;
      this.name = undefined;
      this.DepAndMajorTree = undefined;
    },

    // 学生信息excel表模板下载
    downStudentExcelTemplate() {
      //获取token
      let token = jsCookie.get('sa-token');
      window.location.href =
        this.BASE_API +
        '/admin/student/importStudentDataTemplate?token=' +
        token;
    },
    // 学生信息导出为excel
    exportStudentData() {
      this.$prompt('请输入Excel表名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          //获取token
          let token = jsCookie.get('X-Token');
          let url = '/admin/student/exportStudentData?token=' + token;
          if (value && value != '') {
            url += '&fileName=' + value;
          }
          let ids = '&';
          this.multipleSelection
            .map((item) => item.id)
            .forEach((item) => {
              ids += 'ids=' + item + '&';
            });
          ids = ids.slice(0, ids.length - 1);
          if (ids) {
            url = this.BASE_API + url + ids;
          } else {
            url = this.BASE_API + url;
          }
          // 发送请求
          window.location.href = url;
          // 清空多选
          this.multipleSelection = [];
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入',
          });
        });
    },
    // 文件上传相关函数开始
    // 上传多于一个文件时
    fileUploadExceed() {
      this.$message.warning('只能选取一个文件');
    },
    //上传成功回调：通信成功
    fileUploadSuccess(response) {
      if (response.code === 200) {
        //业务成功
        this.$message.success('数据导入成功');
        this.dialogVisible = false;
        this.getStudentList();
      } else {
        //业务失败
        this.$message.error(response.message);
      }
    },
    //上传失败回调：通信失败
    fileUploadError(error) {
      this.$message.error('数据导入失败');
    },
    // 文件上传相关函数结束
    // 获取学生信息--分页条件查询
    getStudentList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      this.$store.dispatch('StudentMng/getStudentListByCondition', params);
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 学生新增
    handleAdd() {
      // 路由跳转
      this.$router.push({
        name: 'addStudent',
        params: {
          depAndMajorMenu: this.depAndMajorMenu,
        },
      });
    },
    // 获取院系、专业、班级的编号与名称树
    getDepAndMajorAndClassroomMenu() {
      this.$store.dispatch('StudentMng/getDepAndMaJorAndClassroomMenu');
    },
    // 跳转至编辑页面
    handEdit(editStudentInfo) {
      this.$router.push({
        name: 'editStudent',
        params: {
          editStudentInfo,
          depAndMajorMenu: this.depAndMajorMenu,
        },
      });
    },
    // 学生删除---单个
    delStudent(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          let result = await this.$store.dispatch(
            'StudentMng/batchDelStudent',
            [row.id]
          );
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getStudentList();
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 批量删除学生信息
    batchDelStudent() {
      this.$confirm('确定删除所选的学生记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          let params = this.multipleSelection.map((item) => item.id);
          let result = await this.$store.dispatch(
            'StudentMng/batchDelStudent',
            params
          );
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getStudentList();

          // 重置勾选状态
          this.$nextTick(() => {
            this.$refs.studentTable.toggleRowSelection(this.multipleSelection);
            // this.$refs.multipleTable.clearSelection();
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 刷新学生列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getStudentList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getStudentList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getStudentList();
    },
    // 条件查询
    async queryByCondition() {
      let departmentId = this.DepAndMajorTree[0];
      let majorId = this.DepAndMajorTree[1];
      let classroomId = this.DepAndMajorTree[2];
      // 初始化条件查询参数
      this.condition = {};
      if (departmentId) {
        this.condition.departmentId = departmentId;
      }
      if (majorId) {
        this.condition.majorId = majorId;
      }
      if (classroomId) {
        this.condition.classroomId = classroomId;
      }
      if (this.name) {
        this.condition.name = this.name;
      }
      if (this.id) {
        this.condition.id = this.id;
      }

      await this.getStudentList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '~@/styles/variables.scss';

// 文件下载模板 鼠标进入样式
.downFileTemplate {
  color: #409eff;
}
.downFileTemplate:hover {
  color: crimson;
}

// 表格扩展样式
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.function-button {
  margin-bottom: 10px;
}

.tableStyle {
  // height: $tableHeight;
}

/* 分页居中 */
.block {
  text-align: center;
}

// 折叠满样式 -- 搜索栏
.accordion {
  text-align: center;
  div {
    margin-bottom: 20px;
    margin-top: 5px;
  }
  .queryBtn {
    // text-align: center;
  }
}
</style>
